import { CornerstoneViewer } from './cornerstoneViewer';
import { multiBrushManager } from './customBrushManager.js';
import * as cornerstoneTools from 'cornerstone-tools';

// 切换多视图逻辑
export class MultiViewManager {
    constructor() {
        this.currentLayout = '1x1';
        this.viewers = new Map(); // 存储每个视口的查看器实例
        this.activeViewport = 'viewport1';
        this.seriesData = new Map(); // 存储序列数据
        this.onImageChange = null;
        this.brushManager = multiBrushManager; // 添加画笔管理器引用
        
        this.init();
    }

    async init() {
      
        this.setupViewportInteraction();
        
        // 初始化默认的1×1布局
        await this.initializeViewersForLayout('1x1');
    }

    setupViewportInteraction() {
        // 为所有视口添加点击事件
        const viewports = ['viewport1', 'viewport2', 'viewport3', 'viewport4', 'viewport5', 'viewport6', 'viewport7'];
        
        viewports.forEach(viewportId => {
            const viewport = document.getElementById(viewportId);
            if (viewport) {
                viewport.addEventListener('click', () => {
                    this.setActiveViewport(viewportId);
                });
            }
        });
    }

    async switchLayout(layout) {
        console.log(`切换到 ${layout} 布局`);
        // 隐藏所有布局容器
        document.querySelectorAll('.viewport-container').forEach(container => {
            container.style.display = 'none';
        });

        // 显示目标布局容器
        const targetContainer = document.querySelector(`.layout-${layout}`);
        if (targetContainer) {
            targetContainer.style.display = 'grid';
        }

        // 更新当前布局
        this.currentLayout = layout;
        document.getElementById('dicomViewer').setAttribute('data-layout', layout);

        // 根据布局初始化相应的查看器
        await this.initializeViewersForLayout(layout);

        // 重新初始化画笔管理器
        this.reinitializeBrushManagers();


       
    }

    async initializeViewersForLayout(layout) {
        // 清理现有的查看器
        this.cleanupViewers();

        try {
            switch (layout) {
                case '1x1':
                    await this.initializeViewer('viewport1');
                    this.setActiveViewport('viewport1');
                    break;
                case '1x2':
                    await this.initializeViewer('viewport2');
                    await this.initializeViewer('viewport3');
                    this.setActiveViewport('viewport2');
                    break;
                case '2x2':
                    await this.initializeViewer('viewport4');
                    await this.initializeViewer('viewport5');
                    await this.initializeViewer('viewport6');
                    await this.initializeViewer('viewport7');
                    this.setActiveViewport('viewport4');
                    break;
            }

            // 如果有序列数据，重新加载到新的布局中
            console.log('判断当前有没有选中序列',this.seriesData);
            
            if (layout === '1x1' && this.seriesData.size > 0) {
                // 1x1布局使用当前选中的序列
                await this.loadSeriesIntoLayout();
            } else if ((layout === '1x2' || layout === '2x2') && this.allSeriesData && this.allSeriesData.size > 0) {
                // 多视图布局使用所有序列
                await this.loadAllSeriesIntoLayout();
            }



             // 初始化 自定义鼠标标识和下标游标

        // console.log(
        //     '当前工具状态:',
        //     JSON.parse(JSON.stringify())
        //   );
       
  
  console.log('当前工具状态:', cornerstoneTools.store.state.tools);
        //     /=
         
            cornerstoneTools.store.state.tools.forEach((item) => {
                if (item.name == 'EllipticalRoi') { 
                    item.svgCursor.iconGroupString =
                    'https://pic.616pic.com/ys_bnew_img/00/20/12/d4za7gSIBW.jpg';
                    item.svgCursor.options.mousePointerGroupString =
                    '<svg t="1749688820700" class="icon" viewBox="0 0 1142 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="18134" width="24" height="24"><path d="M1056.807385 606.877538c-45.764923 172.347077-204.563692 305.230769-402.195693 334.611693v59.234461h-165.415384v-59.234461c-197.592615-29.380923-356.391385-162.264615-402.116923-334.611693H16.541538v-165.415384h62.109539c30.562462-191.251692 198.104615-342.409846 410.505846-373.996308V8.270769h165.415385v59.234462c212.440615 31.586462 379.982769 182.744615 410.54523 373.996307h62.070154v165.415385h-70.419692z m-61.558154 0h-33.437539v-165.415384h43.323077c-29.892923-158.011077-170.417231-284.199385-350.523077-314.210462V173.686154h-165.415384V127.212308c-180.066462 30.011077-320.590769 156.199385-350.523077 314.210461h43.323077v165.415385h-33.398154c44.071385 139.264 175.773538 247.335385 340.598154 274.786461V835.347692h165.415384v46.355693c164.864-27.451077 296.566154-135.483077 340.637539-274.786462z m-466.668308-472.615384h86.646154v-86.646154h-86.646154v86.646154z m0 827.076923h86.646154v-86.646154h-86.646154v86.646154z m-472.615385-393.846154h86.646154v-86.646154h-86.646154v86.646154z m945.23077 0h86.646154v-86.646154h-86.646154v86.646154z" p-id="18135" fill="#1afa29"></path></svg>';
                }
                if (item.name == 'Pan') {
                    item.svgCursor.iconGroupString =
                        'https://pic.616pic.com/ys_bnew_img/00/20/12/d4za7gSIBW.jpg';
                      item.svgCursor.options.mousePointerGroupString ='<svg t="1749689291447" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="19741" width="24" height="24"><path d="M567.441833 1023.541539c-76.765615 4.264756-153.531231-21.323782-213.23782-72.500859-25.588538-25.588538-51.177077-51.177077-72.500859-81.030372-8.529513-12.794269-17.059026-21.323782-25.588539-34.118051-29.853295-29.853295-63.971346-59.70659-102.354154-81.030372l-25.588538-12.794269c-42.647564-25.588538-81.030372-55.441833-85.295128-93.824641-4.264756-21.323782 4.264756-46.912321 17.059025-63.971347 17.059026-17.059026 38.382808-29.853295 63.971347-29.853295 68.236103-4.264756 119.41318 46.912321 157.795987 93.824642 4.264756 0 8.529513 0 12.794269-8.529513 12.794269-25.588538 8.529513-55.441833-4.264756-81.030372-38.382808-68.236103-89.559885-127.942692-149.266475-174.855013-29.853295-21.323782-42.647564-59.70659-29.853295-93.824641 17.059026-42.647564 63.971346-63.971346 106.618911-46.912321 4.264756 0 8.529513 4.264756 12.794269 8.529513C298.762179 298.532949 358.468769 353.974782 409.645846 413.681372c-17.059026-59.70659-38.382808-149.266474-59.70659-217.502577-8.529513-29.853295-4.264756-59.70659 8.529513-81.030372 17.059026-17.059026 38.382808-29.853295 63.971346-29.853295 34.118051 0 63.971346 17.059026 76.765616 46.912321 38.382808 102.354154 68.236103 204.708308 89.559884 311.327218 12.794269-85.295128 8.529513-174.855013-8.529512-260.150141-8.529513-25.588538-4.264756-51.177077 12.794269-68.236103 12.794269-21.323782 38.382808-29.853295 59.70659-29.853295 34.118051 0 63.971346 21.323782 76.765615 51.177077 29.853295 85.295128 42.647564 174.855013 38.382808 268.679654 8.529513-29.853295 12.794269-63.971346 21.323782-106.61891 4.264756-38.382808 34.118051-72.500859 72.500859-72.500859 21.323782 0 38.382808 8.529513 51.177077 21.323782 17.059026 17.059026 25.588538 42.647564 25.588538 68.236102-4.264756 55.441833-8.529513 106.61891-21.323782 157.795988-4.264756 29.853295-12.794269 59.70659-12.794269 85.295128-4.264756 34.118051-4.264756 68.236103-8.529513 98.089397 0 29.853295-4.264756 59.70659-8.529513 85.295129v8.529512c0 76.765615-29.853295 149.266474-81.030372 200.443552-72.500859 51.177077-153.531231 76.765615-238.826359 72.500859zM136.701436 601.330654h-4.264757c-12.794269 0-25.588538 4.264756-34.118051 12.794269-8.529513 8.529513-12.794269 21.323782-12.794269 29.853295 0 17.059026 34.118051 42.647564 63.971346 59.70659l21.323782 17.059025c42.647564 25.588538 76.765615 55.441833 110.883667 89.559885 8.529513 12.794269 21.323782 21.323782 29.853295 34.118051 21.323782 25.588538 42.647564 51.177077 68.236102 76.765616 51.177077 42.647564 119.41318 63.971346 183.384526 59.70659 72.500859 4.264756 145.001718-17.059026 208.973064-63.971347 46.912321-46.912321 68.236103-110.883667 68.236103-174.855012v-8.529513c4.264756-25.588538 4.264756-55.441833 8.529512-85.295128 4.264756-34.118051 4.264756-63.971346 8.529513-102.354154 4.264756-25.588538 8.529513-55.441833 12.79427-85.295129 12.794269-51.177077 17.059026-102.354154 21.323782-153.53123 0-12.794269-4.264756-25.588538-12.79427-34.118052-4.264756-4.264756-12.794269-8.529513-21.323782-8.529513-17.059026 0-29.853295 12.794269-29.853295 34.118052-8.529513 68.236103-25.588538 132.207449-46.91232 196.178795-4.264756 8.529513-12.794269 12.794269-21.323782 12.794269l-21.323782-4.264756c-12.794269 0-21.323782-12.794269-17.059026-25.588539 0 0 25.588538-196.178795-29.853295-332.651-4.264756-8.529513-21.323782-17.059026-38.382807-17.059026-8.529513 0-21.323782 4.264756-25.588539 12.79427-4.264756 8.529513-8.529513 21.323782-4.264756 34.118051 21.323782 102.354154 21.323782 204.708308 4.264756 307.062461 0 8.529513-8.529513 17.059026-21.323782 17.059026h-29.853295c-8.529513 0-17.059026-8.529513-21.323782-17.059026-21.323782-110.883667-55.441833-221.767333-93.824641-332.651-12.794269-21.323782-42.647564-25.588538-63.971346-8.529512l-4.264757 4.264756c-4.264756 8.529513-8.529513 25.588538 0 38.382808 34.118051 127.942692 81.030372 298.532949 81.030372 298.532948 4.264756 8.529513 0 17.059026-8.529513 25.588539l-17.059025 4.264756c-8.529513 4.264756-21.323782 4.264756-29.853295-8.529512-55.441833-85.295128-127.942692-157.795987-208.973064-217.502577-17.059026-8.529513-38.382808-4.264756-51.177077 12.794269 0 4.264756-4.264756 4.264756-4.264757 8.529513-4.264756 17.059026 0 38.382808 17.059026 46.91232 63.971346 51.177077 115.148423 119.41318 157.795987 187.649282 21.323782 38.382808 25.588538 85.295128 4.264757 123.677936-12.794269 25.588538-38.382808 34.118051-63.971346 21.323782-4.264756 0-8.529513-4.264756-12.79427-8.529513-34.118051-34.118051-72.500859-76.765615-119.413179-76.765615z" fill="#04bf0f" p-id="19742"></path></svg>'; }
              if (item.name == 'Zoom') {  item.svgCursor.iconGroupString =
                'https://pic.616pic.com/ys_bnew_img/00/20/12/d4za7gSIBW.jpg';
              item.svgCursor.options.mousePointerGroupString =
                '<svg t="1749689705537" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="32651" width="24" height="24"><path d="M723.008 656.384l160.448 160.384a42.624 42.624 0 1 1-60.352 60.288l-159.488-159.424a328.576 328.576 0 0 1-204.928 71.68A331.008 331.008 0 0 1 128 458.688 331.008 331.008 0 0 1 458.688 128a331.008 331.008 0 0 1 330.624 330.624 328.32 328.32 0 0 1-66.304 197.76z m-264.32-464.32A266.88 266.88 0 0 0 192 458.688a266.88 266.88 0 0 0 266.624 266.624 266.88 266.88 0 0 0 266.624-266.624A266.88 266.88 0 0 0 458.688 192z" p-id="32652" fill="#04bf0f"></path></svg>'; }
              if (item.name == 'Wwwc') {  item.svgCursor.iconGroupString =
                'https://pic.616pic.com/ys_bnew_img/00/20/12/d4za7gSIBW.jpg';
              item.svgCursor.options.mousePointerGroupString =
                '<svg t="1749689826457" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="35530" width="24" height="24"><path d="M512 870.4c-196.266667 0-358.4-162.133333-358.4-358.4S315.733333 153.6 512 153.6 870.4 315.733333 870.4 512 708.266667 870.4 512 870.4zM512 234.666667c-153.6 0-281.6 128-281.6 281.6s128 281.6 281.6 281.6 281.6-128 281.6-281.6S665.6 234.666667 512 234.666667z" p-id="35531" fill="#04bf0f"></path><path d="M512 211.2c-23.466667 0-38.4-14.933333-38.4-38.4V38.4C473.6 14.933333 488.533333 0 512 0s38.4 14.933333 38.4 38.4v134.4c0 23.466667-14.933333 38.4-38.4 38.4z m-238.933333 100.266667c-10.666667 0-19.2-4.266667-27.733334-10.666667L149.333333 204.8c-14.933333-17.066667-14.933333-38.4 0-55.466667s38.4-14.933333 53.333334 0l96 96c14.933333 14.933333 14.933333 38.4 0 53.333334-6.4 8.533333-17.066667 12.8-25.6 12.8zM172.8 550.4H38.4C14.933333 550.4 0 535.466667 0 512s14.933333-38.4 38.4-38.4h134.4c23.466667 0 38.4 14.933333 38.4 38.4s-19.2 38.4-38.4 38.4z m4.266667 334.933333c-10.666667 0-19.2-4.266667-27.733334-10.666666-14.933333-14.933333-14.933333-38.4 0-53.333334l96-96c14.933333-14.933333 38.4-14.933333 53.333334 0s14.933333 38.4 0 53.333334L204.8 874.666667c-8.533333 6.4-17.066667 10.666667-27.733333 10.666666zM512 1024c-23.466667 0-38.4-14.933333-38.4-38.4v-134.4c0-23.466667 14.933333-38.4 38.4-38.4s38.4 14.933333 38.4 38.4v134.4c0 23.466667-14.933333 38.4-38.4 38.4z m334.933333-138.666667c-10.666667 0-19.2-4.266667-27.733333-10.666666l-96-96c-14.933333-14.933333-14.933333-38.4 0-53.333334s38.4-14.933333 53.333333 0l96 96c14.933333 14.933333 14.933333 38.4 0 53.333334-6.4 6.4-14.933333 10.666667-25.6 10.666666z m138.666667-334.933333h-134.4c-23.466667 0-38.4-14.933333-38.4-38.4s14.933333-38.4 38.4-38.4h134.4c23.466667 0 38.4 14.933333 38.4 38.4s-14.933333 38.4-38.4 38.4z m-234.666667-238.933333c-10.666667 0-19.2-4.266667-27.733333-10.666667-14.933333-14.933333-14.933333-38.4 0-53.333333L819.2 149.333333c14.933333-14.933333 38.4-14.933333 53.333333 0s14.933333 38.4 0 53.333334L776.533333 298.666667c-6.4 8.533333-14.933333 12.8-25.6 12.8z m-258.133333-14.933334c-110.933333 8.533333-204.8 104.533333-204.8 219.733334s89.6 206.933333 204.8 219.733333V296.533333z" p-id="35532" fill="#04bf0f"></path></svg>'; }

             })

        } catch (error) {
            console.error('初始化视图布局失败:', error);
        }
    }

    async initializeViewer(viewportId) {
        try {
            console.log(`初始化查看器: ${viewportId}`);
            
            const viewer = new CornerstoneViewer();
            await viewer.initialize(viewportId);
            
            this.viewers.set(viewportId, viewer);
            
            // 清除占位符
            const viewport = document.getElementById(viewportId);
            const placeholder = viewport.querySelector('.viewer-placeholder');
            if (placeholder) {
                placeholder.style.display = 'none';
            }
            
        } catch (error) {
            console.error(`初始化查看器 ${viewportId} 失败:`, error);
        }
    }

    cleanupViewers() {
        // 销毁现有的查看器实例
        this.viewers.forEach((viewer, viewportId) => {
            try {
                viewer.destroy();
            } catch (error) {
                console.warn(`销毁查看器 ${viewportId} 时出错:`, error);
            }
        });
        this.viewers.clear();
    }

    setActiveViewport(viewportId) {
        // 移除所有视口的活动状态
        document.querySelectorAll('.viewport').forEach(viewport => {
            viewport.classList.remove('active');
        });

        // 设置新的活动视口
        const viewport = document.getElementById(viewportId);
        if (viewport) {
            viewport.classList.add('active');
            this.activeViewport = viewportId;
            console.log(`活动视口设置为: ${viewportId}`,viewport);
        }
    }

    getActiveViewer() {
        return this.viewers.get(this.activeViewport);
    }

    getAllViewers() {
        return Array.from(this.viewers.values());
    }

    // 设置序列数据
    async setSeriesData(seriesData, imageIndex = 0, onImageChange = null) {
        this.seriesData = seriesData;
        this.onImageChange = onImageChange;
        
        await this.loadSeriesIntoLayout(imageIndex);
    }

    // 设置所有序列数据（用于多视图模式）
    async setAllSeriesData(allSeriesData, imageIndex = 0, onImageChange = null) {
        this.allSeriesData = allSeriesData;
        this.onImageChange = onImageChange;
        
        // 根据当前布局加载相应数量的序列
        await this.loadAllSeriesIntoLayout(imageIndex);
    }

    async loadSeriesIntoLayout(imageIndex = 0) {
        if (this.seriesData.size === 0) return;

        const seriesArray = Array.from(this.seriesData.values());
        const activeViewers = Array.from(this.viewers.values());

        try {
            switch (this.currentLayout) {
                case '1x1':
                    // 单视图：显示第一个序列
                    if (seriesArray.length > 0 && activeViewers.length > 0) {
                        await activeViewers[0].setSeriesData(seriesArray[0], imageIndex, this.onImageChange);
                    }
                    break;

                case '1x2':
                    // 双视图：根据当前活动视口显示序列
                    if (seriesArray.length > 0) {
                        const activeViewportId = this.activeViewport || 'viewport2';
                        const activeViewerIndex = activeViewportId === 'viewport2' ? 0 : 1;
                        
                        // 确保索引在有效范围内
                        if (activeViewerIndex < activeViewers.length) {
                            await activeViewers[activeViewerIndex].setSeriesData(seriesArray[0], imageIndex, this.onImageChange);
                        }
                    }
                    break;

                case '2x2':
                    // 四视图：显示前四个序列
                    for (let i = 0; i < Math.min(4, seriesArray.length, activeViewers.length); i++) {
                        await activeViewers[i].setSeriesData(seriesArray[i], imageIndex, this.onImageChange);
                    }
                    break;
            }
        } catch (error) {
            console.error('加载序列到布局失败:', error);
        }
    }

    async loadAllSeriesIntoLayout(imageIndex = 0) {
        if (!this.allSeriesData || this.allSeriesData.size === 0) return;

        const seriesArray = Array.from(this.allSeriesData.values());
        const activeViewers = Array.from(this.viewers.values());

        try {
            switch (this.currentLayout) {
                case '1x1':
                    // 单视图：显示第一个序列
                    if (seriesArray.length > 0 && activeViewers.length > 0) {
                        await activeViewers[0].setSeriesData(seriesArray[0], imageIndex, this.onImageChange);
                    }
                    break;

                case '1x2':
                    // 双视图：显示前两个序列
                    for (let i = 0; i < Math.min(2, seriesArray.length, activeViewers.length); i++) {
                        await activeViewers[i].setSeriesData(seriesArray[i], imageIndex, this.onImageChange);
                    }
                    break;

                case '2x2':
                    // 四视图：显示前四个序列
                    for (let i = 0; i < Math.min(4, seriesArray.length, activeViewers.length); i++) {
                        await activeViewers[i].setSeriesData(seriesArray[i], imageIndex, this.onImageChange);
                    }
                    break;
            }
        } catch (error) {
            console.error('加载所有序列到布局失败:', error);
        }
    }

    // 导航到指定图像（所有视图同步）
    navigateToImage(index) {
        this.viewers.forEach(viewer => {
            try {
                viewer.navigateToImage(index);
            } catch (error) {
                console.warn('导航图像失败:', error);
            }
        });
    }

    // 设置窗宽窗位（所有视图同步）
    setWindowLevel(width, center) {
        this.viewers.forEach(viewer => {
            try {
                viewer.setWindowLevel(width, center);
            } catch (error) {
                console.warn('设置窗宽窗位失败:', error);
            }
        });
    }

    // 重置视图（所有视图）
    resetView() {
        this.viewers.forEach(viewer => {
            try {
                viewer.resetView();
            } catch (error) {
                console.warn('重置视图失败:', error);
            }
        });
    }

    // 适应窗口（所有视图）
    fitToWindow() {
        this.viewers.forEach(viewer => {
            try {
                viewer.fitToWindow();
            } catch (error) {
                console.warn('适应窗口失败:', error);
            }
        });
    }

    // 缩放（所有视图）
    zoomIn() {
        const activeViewer = this.getActiveViewer();
        if (activeViewer) {
            activeViewer.zoomIn();
        }
    }

    zoomOut() {
        const activeViewer = this.getActiveViewer();
        if (activeViewer) {
            activeViewer.zoomOut();
        }
    }

    // 旋转（活动视图）
    rotate(degrees) {
        const activeViewer = this.getActiveViewer();
        if (activeViewer) {
            activeViewer.rotate(degrees);
        }
    }

    // 翻转（活动视图）
    flipHorizontal() {
        const activeViewer = this.getActiveViewer();
        if (activeViewer) {
            activeViewer.flipHorizontal();
        }
    }

    flipVertical() {
        const activeViewer = this.getActiveViewer();
        if (activeViewer) {
            activeViewer.flipVertical();
        }
    }

    // 激活测量工具（活动视图）
    activateLengthTool() {
        const activeViewer = this.getActiveViewer();
        if (activeViewer) {
            activeViewer.activateLengthTool();
        }
    }

    activateAngleTool() {
        const activeViewer = this.getActiveViewer();
        if (activeViewer) {
            activeViewer.activateAngleTool();
        }
    }

    activateRectangleRoiTool() {
        const activeViewer = this.getActiveViewer();
        if (activeViewer) {
            activeViewer.activateRectangleRoiTool();
        }
    }

    activateWwwcTool() {
        const activeViewer = this.getActiveViewer();
        if (activeViewer) {
            activeViewer.activateWwwcTool();
        }
    }

    // 激活移动工具
    activatePanTool() {
        const activeViewer = this.getActiveViewer();
        if (activeViewer) {
            activeViewer.activatePanTool();
        }
    }

    // 清除测量（所有视图）
    clearMeasurements() {
        this.viewers.forEach(viewer => {
            try {
                viewer.clearMeasurements();
            } catch (error) {
                console.warn('清除测量失败:', error);
            }
        });
    }

    // 导出图像（活动视图）
    exportImage() {
        const activeViewer = this.getActiveViewer();
        if (activeViewer) {
            activeViewer.exportImage();
        }
    }

    // 获取视口信息（活动视图）
    getViewportInfo() {
        const activeViewer = this.getActiveViewer();
        if (activeViewer) {
            return activeViewer.getViewportInfo();
        }
        return null;
    }

    // 销毁管理器
    destroy() {
        this.cleanupViewers();
        this.seriesData.clear();
    }

    // 重新初始化画笔管理器
    reinitializeBrushManagers() {
        // 获取当前布局的所有视口
        const viewportIds = this.getViewportIdsForCurrentLayout();
        
        if (viewportIds.length > 0) {
            // 为每个视口初始化画笔管理器
            viewportIds.forEach(viewportId => {
                const viewportElement = document.getElementById(viewportId);
                if (viewportElement) {
                    this.brushManager.initializeBrushForViewport(viewportElement, viewportId);
                }
            });
            
            console.log(`为 ${viewportIds.length} 个视口重新初始化画笔管理器`);
        }
    }

    // 获取当前布局的视口ID列表
    getViewportIdsForCurrentLayout() {
        switch (this.currentLayout) {
            case '1x1':
                return ['viewport1'];
            case '1x2':
                return ['viewport2', 'viewport3'];
            case '2x2':
                return ['viewport4', 'viewport5', 'viewport6', 'viewport7'];
            default:
                return ['viewport1'];
        }
    }
} 